/**
 * 用户相关操作的接口
 */
const express = require("express")
const router = express.Router()
const pool = require("../../db/db")
// 引入发送邮件的模块
const nodemailer = require("nodemailer")
const { generateToken } = require("../../auth/jwt")
const Response = require("../../utils/ResponseData")
const random = require("../../utils/Random")

/**
 * 校验邮箱是否已注册的接口
 * 请求url：http://localhost:3001/user/checkEmail
 * 请求method：post
 * 请求params：req.body
 */
router.post("/checkEmail", (req, res, next) => {
    // 获取表单传递的邮箱
    let { email } = req.body
    // 编写sql
    let sql = `select * from user where u_email = ?`
    // 执行sql
    pool.query(sql, [email], (err, data) => {
        if (err) {
            console.log("/user/checkEmail接口：", err)
            next(err)
            return;
        }
        if (data.length == 0) {
            res.send(Response.success(null, "该邮箱可以使用！"))
        } else {
            res.send(Response.error("该邮箱已被注册！"))
        }
    })
})

/**
 * 发送邮箱验证码接口
 * 请求url：http://localhost:3001/user/sendCode
 * 请求method：post
 * 请求params：req.body=>  email
 */
router.post("/sendCode", (req, res, next) => {
    // 生成4位数字验证码 1000~9999  0~1 0~999
    let code = random(1000, 9999)
    // 获取传递过来的邮箱号
    let { email } = req.body
    // 编写sql
    let sql = `insert into user_code values(?,?)`
    // 执行sql
    pool.query(sql, [email, code], (err, data) => {
        if (err) {
            console.log("/user/sendCode接口：", err)
            next(err)
            return;
        }
        // 发送邮件
        // 需要制作一个邮件模板
        let transporter = nodemailer.createTransport({
            host: 'smtp.qq.com',
            secureConnection: true,
            port: 465,
            auth: {
                user: '2506075234@qq.com', // 邮箱账号
                pass: "vfhuzyyhbearebjh" // 授权码
            }
        })
        // 配置相关参数
        let options = {
            from: "2506075234@qq.com",// 发送者
            to: `${email},2506075234@qq.com`,// 接收者，也就是用户的注册邮箱
            // 邮箱标题
            subject: "宠物伴伴有限责任公司",
            // 邮件内容模板
            html: `
            <!DOCTYPE html>
            <html lang="en">
            
            <head>
                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Document</title>
            </head>
            
            <body>
                <div class="center">
                    <h3>尊敬的用户您好：</h3>
                    <p>欢迎您注册宠物伴伴，您的验证码是${code}，请注意查收！</p>
                </div>
            </body>
            
            </html>
            
            `
        }
        // 发送邮件
        transporter.sendMail(options, (err, msg) => {
            console.log("发送邮件：", err, msg)
            if (err) {

                //res.send(Response.error(err))
            } else {
                res.send(Response.success(null, msg))
            }
        })

    })
})
/**
 * 邮箱验证码是否正确接口
 * 请求url：http://localhost:3001/user/checkCode
 * 请求method：post
 * 请求params：req.body => email,code
 */
router.post("/checkCode", (req, res, next) => {
    // 获取前端传递的邮箱，验证码
    let { email, code } = req.body;
    // joi校验，大家自行添加
    // 编写sql
    let sql = "select * from user_code where u_email =? and u_code=?"
    // 执行sql
    pool.query(sql, [email, code], (err, data) => {
        if (err) {
            console.log("/user/checkCode接口：", err)
            next(err)
            return
        }
        if (data.length == 0) {
            res.send(Response.error("验证码输入有误！"))
        } else {
            res.send(Response.success(null, "验证码输入正确！"))
        }
    })
})
/**
 * 用户注册接口
 * 请求url：http://localhost:3001/user/register
 * 请求method；post
 * 请求params:req.body => uName,uEmail,uPwd
 */
router.post("/register", (req, res, next) => {
    // 获取前端请求参数
    let { uName, uEmail, uPwd } = req.body
    // joi校验
    // 编写sql
    let sql = "insert into user(u_name,u_email,u_pwd) values (?,?,?)"
    // 执行sql
    pool.query(sql, [uName, uEmail, uPwd], (err, data) => {
        if (err) {
            console.log("/user/register接口：", err)
            next(err)
            return
        }

        if (data.affectedRows > 0) {
            res.send(Response.success(null, "用户注册成功！"))
        } else {
            res.send(Response.error("用户注册失败！"))
        }

    })

})
// 用户登录接口
router.post("/login", (req, res, next) => {
    let { u_email, u_pwd } = req.body
    let sql = "select * from user where u_email = ? and u_pwd = ?"
    pool.query(sql, [u_email, u_pwd], (err, data) => {
        console.log(data)
        if (err) {
            console.log("/user/login接口：", err)
            next(err)
            return
        }

        if (data.length == 0) {
            res.send(Response.error("登录失败，用户信息不存在"))
        } else {
            const token = generateToken(data[0].u_id, 2)
            res.send(Response.success({
                u_id: data[0].u_id,
                u_name: data[0].u_name,
                token: "Bearer " + token
            }, "登录成功"))
        }
    })
})
module.exports = router